using System.Diagnostics;

namespace DeviceDataGenerator
{
    /// <summary>
    /// 测试配置
    /// </summary>
    public class TestConfig
    {
        public string DeviceName { get; set; } = string.Empty;
        public int ReadingCount { get; set; }
        public int StateCount { get; set; }
        public bool UseEncryption { get; set; }
        public bool UseCompression { get; set; }
        public string? Password { get; set; }
    }

    /// <summary>
    /// 测试结果
    /// </summary>
    public class TestResult
    {
        public TestConfig Config { get; set; } = new();
        public long BuildTime { get; set; }      // Ticks
        public long SerializeTime { get; set; }  // Ticks
        public long ParseTime { get; set; }      // Ticks
        public int MessageSize { get; set; }     // 字符数
        public bool Success { get; set; }
        
        // 新增：CPU和内存监控
        public double CpuUsagePercent { get; set; }    // CPU使用率(%)
        public long MemoryUsageBytes { get; set; }      // 内存使用量(字节)
        public DateTime Timestamp { get; set; } = DateTime.Now; // 时间戳
        
        /// <summary>
        /// 总耗时（毫秒）
        /// </summary>
        public double TotalTimeMs => (BuildTime + SerializeTime + ParseTime) * 1000.0 / Stopwatch.Frequency;
        
        /// <summary>
        /// 构建时间（毫秒）
        /// </summary>
        public double BuildTimeMs => BuildTime * 1000.0 / Stopwatch.Frequency;
        
        /// <summary>
        /// 序列化时间（毫秒）
        /// </summary>
        public double SerializeTimeMs => SerializeTime * 1000.0 / Stopwatch.Frequency;
        
        /// <summary>
        /// 解析时间（毫秒）
        /// </summary>
        public double ParseTimeMs => ParseTime * 1000.0 / Stopwatch.Frequency;
    }

    /// <summary>
    /// 性能统计
    /// </summary>
    public class PerformanceStats
    {
        private readonly DateTime _startTime = DateTime.Now;
        private readonly List<TestResult> _results = new();
        
        // 新增：独立的总计数器，不受数据清理影响
        private int _totalTestCount = 0;
        private int _totalSuccessCount = 0;
        
        // 新增：千次移动平均计算器
        private readonly MovingAverage<double> _buildTimeMA = new(1000);
        private readonly MovingAverage<double> _serializeTimeMA = new(1000);
        private readonly MovingAverage<double> _parseTimeMA = new(1000);
        private readonly MovingAverage<double> _cpuUsageMA = new(1000);
        private readonly MovingAverage<long> _memoryUsageMA = new(1000);
        
        // 新增：数据大小分段统计
        private readonly Dictionary<DataSizeSegment, List<TestResult>> _segmentResults = new()
        {
            { DataSizeSegment.Small, new List<TestResult>() },
            { DataSizeSegment.Medium, new List<TestResult>() },
            { DataSizeSegment.Large, new List<TestResult>() },
            { DataSizeSegment.ExtraLarge, new List<TestResult>() }
        };
        
        private readonly Dictionary<DataSizeSegment, MovingAverage<double>> _segmentParseTimeMA = new()
        {
            { DataSizeSegment.Small, new MovingAverage<double>(1000) },
            { DataSizeSegment.Medium, new MovingAverage<double>(1000) },
            { DataSizeSegment.Large, new MovingAverage<double>(1000) },
            { DataSizeSegment.ExtraLarge, new MovingAverage<double>(1000) }
        };
        
        // 新增：加密状态细分的移动平均计算器
        private readonly Dictionary<DataSizeSegment, MovingAverage<double>> _segmentEncryptedParseTimeMA = new()
        {
            { DataSizeSegment.Small, new MovingAverage<double>(1000) },
            { DataSizeSegment.Medium, new MovingAverage<double>(1000) },
            { DataSizeSegment.Large, new MovingAverage<double>(1000) },
            { DataSizeSegment.ExtraLarge, new MovingAverage<double>(1000) }
        };
        
        private readonly Dictionary<DataSizeSegment, MovingAverage<double>> _segmentUnencryptedParseTimeMA = new()
        {
            { DataSizeSegment.Small, new MovingAverage<double>(1000) },
            { DataSizeSegment.Medium, new MovingAverage<double>(1000) },
            { DataSizeSegment.Large, new MovingAverage<double>(1000) },
            { DataSizeSegment.ExtraLarge, new MovingAverage<double>(1000) }
        };
        
        // 新增：压缩状态细分的移动平均计算器
        private readonly Dictionary<DataSizeSegment, MovingAverage<double>> _segmentCompressedParseTimeMA = new()
        {
            { DataSizeSegment.Small, new MovingAverage<double>(1000) },
            { DataSizeSegment.Medium, new MovingAverage<double>(1000) },
            { DataSizeSegment.Large, new MovingAverage<double>(1000) },
            { DataSizeSegment.ExtraLarge, new MovingAverage<double>(1000) }
        };
        
        private readonly Dictionary<DataSizeSegment, MovingAverage<double>> _segmentUncompressedParseTimeMA = new()
        {
            { DataSizeSegment.Small, new MovingAverage<double>(1000) },
            { DataSizeSegment.Medium, new MovingAverage<double>(1000) },
            { DataSizeSegment.Large, new MovingAverage<double>(1000) },
            { DataSizeSegment.ExtraLarge, new MovingAverage<double>(1000) }
        };
        
        // 总体统计（使用独立计数器，不受数据清理影响）
        public int TotalTests => _totalTestCount;
        public int SuccessCount => _totalSuccessCount;
        public double SuccessRate => TotalTests > 0 ? (double)SuccessCount / TotalTests : 0;
        
        // 构建性能
        public double AverageBuildTime => _results.Count > 0 ? _results.Average(r => r.BuildTimeMs) : 0;
        public double MinBuildTime => _results.Count > 0 ? _results.Min(r => r.BuildTimeMs) : 0;
        public double MaxBuildTime => _results.Count > 0 ? _results.Max(r => r.BuildTimeMs) : 0;
        public double MovingAverageBuildTime => _buildTimeMA.Average;
        
        // 序列化性能
        public double AverageSerializeTime => _results.Count > 0 ? _results.Average(r => r.SerializeTimeMs) : 0;
        public double MinSerializeTime => _results.Count > 0 ? _results.Min(r => r.SerializeTimeMs) : 0;
        public double MaxSerializeTime => _results.Count > 0 ? _results.Max(r => r.SerializeTimeMs) : 0;
        public double MovingAverageSerializeTime => _serializeTimeMA.Average;
        
        // 解析性能
        public double AverageParseTime => _results.Count > 0 ? _results.Average(r => r.ParseTimeMs) : 0;
        public double MinParseTime => _results.Count > 0 ? _results.Min(r => r.ParseTimeMs) : 0;
        public double MaxParseTime => _results.Count > 0 ? _results.Max(r => r.ParseTimeMs) : 0;
        public double MovingAverageParseTime => _parseTimeMA.Average;
        
        // CPU统计
        public double AverageCpuUsage => _results.Count > 0 ? _results.Average(r => r.CpuUsagePercent) : 0;
        public double MinCpuUsage => _results.Count > 0 ? _results.Min(r => r.CpuUsagePercent) : 0;
        public double MaxCpuUsage => _results.Count > 0 ? _results.Max(r => r.CpuUsagePercent) : 0;
        public double MovingAverageCpuUsage => _cpuUsageMA.Average;
        
        // 内存统计
        public double AverageMemoryUsageMB => _results.Count > 0 ? _results.Average(r => r.MemoryUsageBytes / (1024.0 * 1024.0)) : 0;
        public double MinMemoryUsageMB => _results.Count > 0 ? _results.Min(r => r.MemoryUsageBytes / (1024.0 * 1024.0)) : 0;
        public double MaxMemoryUsageMB => _results.Count > 0 ? _results.Max(r => r.MemoryUsageBytes / (1024.0 * 1024.0)) : 0;
        public double MovingAverageMemoryUsageMB => _memoryUsageMA.Average / (1024.0 * 1024.0);
        
        /// <summary>
        /// 根据数据大小获取分段
        /// </summary>
        /// <param name="dataSize">数据大小（字符数）</param>
        /// <returns>分段类型</returns>
        public static DataSizeSegment GetDataSizeSegment(int dataSize)
        {
            // 按字符数分段（假设一个字符约等于0.5字节）
            var bytes = dataSize / 2; // 粗略估算
            
            return bytes switch
            {
                <= 1024 => DataSizeSegment.Small,      // 0-1KB
                <= 10240 => DataSizeSegment.Medium,    // 1KB-10KB  
                <= 102400 => DataSizeSegment.Large,    // 10KB-100KB
                _ => DataSizeSegment.ExtraLarge        // >100KB
            };
        }
        
        /// <summary>
        /// 获取分段名称
        /// </summary>
        /// <param name="segment">分段类型</param>
        /// <returns>分段名称</returns>
        public static string GetSegmentName(DataSizeSegment segment)
        {
            return segment switch
            {
                DataSizeSegment.Small => "小消息 (0-1KB)     ",
                DataSizeSegment.Medium => "中等消息 (1KB-10KB)",
                DataSizeSegment.Large => "大消息 (10KB-100KB)",
                DataSizeSegment.ExtraLarge => "超大消息 (>100KB)",
                _ => "未知"
            };
        }
        
        // 加密对比
        public int EncryptedCount => _results.Count(r => r.Config.UseEncryption);
        public int UnencryptedCount => _results.Count(r => !r.Config.UseEncryption);
        public double EncryptedAverageTime => EncryptedCount > 0 ? 
            _results.Where(r => r.Config.UseEncryption).Average(r => r.TotalTimeMs) : 0;
        public double UnencryptedAverageTime => UnencryptedCount > 0 ? 
            _results.Where(r => !r.Config.UseEncryption).Average(r => r.TotalTimeMs) : 0;
        public double EncryptionOverhead => EncryptedAverageTime - UnencryptedAverageTime;
        
        // 压缩对比
        public int CompressedCount => _results.Count(r => r.Config.UseCompression);
        public int UncompressedCount => _results.Count(r => !r.Config.UseCompression);
        public double CompressedAverageTime => CompressedCount > 0 ? 
            _results.Where(r => r.Config.UseCompression).Average(r => r.TotalTimeMs) : 0;
        public double UncompressedAverageTime => UncompressedCount > 0 ? 
            _results.Where(r => !r.Config.UseCompression).Average(r => r.TotalTimeMs) : 0;
        public double CompressionOverhead => CompressedAverageTime - UncompressedAverageTime;
        
        // 消息大小对比
        public double CompressedAverageSize => CompressedCount > 0 ? 
            _results.Where(r => r.Config.UseCompression).Average(r => r.MessageSize) : 0;
        public double UncompressedAverageSize => UncompressedCount > 0 ? 
            _results.Where(r => !r.Config.UseCompression).Average(r => r.MessageSize) : 0;
        
        // 吞吐量统计
        public double TestsPerSecond
        {
            get
            {
                var elapsed = DateTime.Now - _startTime;
                return elapsed.TotalSeconds > 0 ? TotalTests / elapsed.TotalSeconds : 0;
            }
        }
        
        public double BuildsPerSecond => TestsPerSecond; // 每个测试都包含构建
        public double ParsesPerSecond => TestsPerSecond;  // 每个测试都包含解析
        
        /// <summary>
        /// 添加测试结果
        /// </summary>
        public void AddResult(TestResult result)
        {
            // 更新独立计数器（不受数据清理影响）
            _totalTestCount++;
            if (result.Success)
            {
                _totalSuccessCount++;
            }
            
            _results.Add(result);
            
            // 更新千次移动平均
            _buildTimeMA.Add(result.BuildTimeMs);
            _serializeTimeMA.Add(result.SerializeTimeMs);
            _parseTimeMA.Add(result.ParseTimeMs);
            _cpuUsageMA.Add(result.CpuUsagePercent);
            _memoryUsageMA.Add(result.MemoryUsageBytes);
            
            // 添加到数据大小分段统计
            var segment = GetDataSizeSegment(result.MessageSize);
            _segmentResults[segment].Add(result);
            _segmentParseTimeMA[segment].Add(result.ParseTimeMs);
            
            // 添加到加密状态细分统计
            if (result.Config.UseEncryption)
            {
                _segmentEncryptedParseTimeMA[segment].Add(result.ParseTimeMs);
            }
            else
            {
                _segmentUnencryptedParseTimeMA[segment].Add(result.ParseTimeMs);
            }
            
            // 添加到压缩状态细分统计
            if (result.Config.UseCompression)
            {
                _segmentCompressedParseTimeMA[segment].Add(result.ParseTimeMs);
            }
            else
            {
                _segmentUncompressedParseTimeMA[segment].Add(result.ParseTimeMs);
            }
            
            // 保持最近的记录，避免内存无限增长（但不影响总计数）
            if (_results.Count > 10000)
            {
                _results.RemoveRange(0, 1000);
            }
            
            // 清理各分段的历史数据（不影响总计数）
            foreach (var segmentList in _segmentResults.Values)
            {
                if (segmentList.Count > 2000)
                {
                    segmentList.RemoveRange(0, 200);
                }
            }
        }
        
        /// <summary>
        /// 获取运行时间
        /// </summary>
        public string GetRunningTime()
        {
            var elapsed = DateTime.Now - _startTime;
            return $"{elapsed.Hours:D2}:{elapsed.Minutes:D2}:{elapsed.Seconds:D2}";
        }
        
        /// <summary>
        /// 重置统计
        /// </summary>
        public void Reset()
        {
            _results.Clear();
            
            // 清空移动平均计算器
            _buildTimeMA.Clear();
            _serializeTimeMA.Clear();
            _parseTimeMA.Clear();
            _cpuUsageMA.Clear();
            _memoryUsageMA.Clear();
            
            // 清空分段统计数据
            foreach (var segmentList in _segmentResults.Values)
            {
                segmentList.Clear();
            }
            foreach (var segmentMA in _segmentParseTimeMA.Values)
            {
                segmentMA.Clear();
            }
            
            // 清空加密状态细分移动平均计算器
            foreach (var segmentMA in _segmentEncryptedParseTimeMA.Values)
            {
                segmentMA.Clear();
            }
            foreach (var segmentMA in _segmentUnencryptedParseTimeMA.Values)
            {
                segmentMA.Clear();
            }
            
            // 清空压缩状态细分移动平均计算器
            foreach (var segmentMA in _segmentCompressedParseTimeMA.Values)
            {
                segmentMA.Clear();
            }
            foreach (var segmentMA in _segmentUncompressedParseTimeMA.Values)
            {
                segmentMA.Clear();
            }
        }
        
        /// <summary>
        /// 获取详细统计信息
        /// </summary>
        public DetailedStats GetDetailedStats()
        {
            return new DetailedStats
            {
                // 总体统计
                TotalTests = this.TotalTests,
                SuccessRate = this.SuccessRate,
                RunningTime = DateTime.Now - _startTime,
                
                // 构建统计
                BuildStats = new OperationStats
                {
                    Average = this.AverageBuildTime,
                    Min = this.MinBuildTime,
                    Max = this.MaxBuildTime,
                    MovingAverage = this.MovingAverageBuildTime,
                    Median = CalculateMedian(_results.Select(r => r.BuildTimeMs)),
                    P95 = CalculatePercentile(_results.Select(r => r.BuildTimeMs), 0.95),
                    P99 = CalculatePercentile(_results.Select(r => r.BuildTimeMs), 0.99)
                },
                
                // 序列化统计
                SerializeStats = new OperationStats
                {
                    Average = this.AverageSerializeTime,
                    Min = this.MinSerializeTime,
                    Max = this.MaxSerializeTime,
                    MovingAverage = this.MovingAverageSerializeTime,
                    Median = CalculateMedian(_results.Select(r => r.SerializeTimeMs)),
                    P95 = CalculatePercentile(_results.Select(r => r.SerializeTimeMs), 0.95),
                    P99 = CalculatePercentile(_results.Select(r => r.SerializeTimeMs), 0.99)
                },
                
                // 解析统计
                ParseStats = new OperationStats
                {
                    Average = this.AverageParseTime,
                    Min = this.MinParseTime,
                    Max = this.MaxParseTime,
                    MovingAverage = this.MovingAverageParseTime,
                    Median = CalculateMedian(_results.Select(r => r.ParseTimeMs)),
                    P95 = CalculatePercentile(_results.Select(r => r.ParseTimeMs), 0.95),
                    P99 = CalculatePercentile(_results.Select(r => r.ParseTimeMs), 0.99)
                },
                
                // 系统资源统计
                SystemStats = new SystemResourceStats
                {
                    AverageCpuUsage = this.AverageCpuUsage,
                    MinCpuUsage = this.MinCpuUsage,
                    MaxCpuUsage = this.MaxCpuUsage,
                    MovingAverageCpuUsage = this.MovingAverageCpuUsage,
                    AverageMemoryUsageMB = this.AverageMemoryUsageMB,
                    MinMemoryUsageMB = this.MinMemoryUsageMB,
                    MaxMemoryUsageMB = this.MaxMemoryUsageMB,
                    MovingAverageMemoryUsageMB = this.MovingAverageMemoryUsageMB
                },
                
                // 加密对比
                EncryptionComparison = new ComparisonStats
                {
                    WithFeatureCount = this.EncryptedCount,
                    WithoutFeatureCount = this.UnencryptedCount,
                    WithFeatureAverage = this.EncryptedAverageTime,
                    WithoutFeatureAverage = this.UnencryptedAverageTime,
                    Overhead = this.EncryptionOverhead
                },
                
                // 压缩对比
                CompressionComparison = new ComparisonStats
                {
                    WithFeatureCount = this.CompressedCount,
                    WithoutFeatureCount = this.UncompressedCount,
                    WithFeatureAverage = this.CompressedAverageTime,
                    WithoutFeatureAverage = this.UncompressedAverageTime,
                    Overhead = this.CompressionOverhead,
                    WithFeatureSize = this.CompressedAverageSize,
                    WithoutFeatureSize = this.UncompressedAverageSize
                },
                
                // 吞吐量
                Throughput = new ThroughputStats
                {
                    TestsPerSecond = this.TestsPerSecond,
                    BuildsPerSecond = this.BuildsPerSecond,
                    ParsesPerSecond = this.ParsesPerSecond
                }
            };
        }
        
        /// <summary>
        /// 计算中位数
        /// </summary>
        private static double CalculateMedian(IEnumerable<double> values)
        {
            var sorted = values.OrderBy(x => x).ToArray();
            if (sorted.Length == 0) return 0;
            
            if (sorted.Length % 2 == 0)
            {
                return (sorted[sorted.Length / 2 - 1] + sorted[sorted.Length / 2]) / 2;
            }
            else
            {
                return sorted[sorted.Length / 2];
            }
        }
        
        /// <summary>
        /// 计算百分位数
        /// </summary>
        private static double CalculatePercentile(IEnumerable<double> values, double percentile)
        {
            var sorted = values.OrderBy(x => x).ToArray();
            if (sorted.Length == 0) return 0;
            
            var index = (int)Math.Ceiling(sorted.Length * percentile) - 1;
            return sorted[Math.Min(index, sorted.Length - 1)];
        }
        
        /// <summary>
        /// 获取按数据大小分段的解析时间统计
        /// </summary>
        /// <returns>各分段的统计信息</returns>
        public IEnumerable<ParseTimeSegmentStats> GetParseTimeSegmentStats()
        {
            foreach (var segment in Enum.GetValues<DataSizeSegment>())
            {
                var results = _segmentResults[segment];
                if (results.Count == 0)
                    continue;
                
                // 加密状态统计
                var encryptedResults = results.Where(r => r.Config.UseEncryption).ToList();
                var unencryptedResults = results.Where(r => !r.Config.UseEncryption).ToList();
                
                // 压缩状态统计
                var compressedResults = results.Where(r => r.Config.UseCompression).ToList();
                var uncompressedResults = results.Where(r => !r.Config.UseCompression).ToList();
                    
                yield return new ParseTimeSegmentStats
                {
                    Segment = segment,
                    SegmentName = GetSegmentName(segment),
                    Count = results.Count,
                    AverageParseTime = results.Average(r => r.ParseTimeMs),
                    MinParseTime = results.Min(r => r.ParseTimeMs),
                    MaxParseTime = results.Max(r => r.ParseTimeMs),
                    MovingAverageParseTime = _segmentParseTimeMA[segment].Average,
                    AverageDataSize = results.Average(r => r.MessageSize / 2.0), // 转换为字节估算
                    TotalDataProcessed = results.Sum(r => r.MessageSize / 2), // 转换为字节估算
                    
                    // 加密状态统计
                    EncryptedCount = encryptedResults.Count,
                    UnencryptedCount = unencryptedResults.Count,
                    EncryptedAverageParseTime = encryptedResults.Count > 0 ? encryptedResults.Average(r => r.ParseTimeMs) : 0,
                    UnencryptedAverageParseTime = unencryptedResults.Count > 0 ? unencryptedResults.Average(r => r.ParseTimeMs) : 0,
                    EncryptedMovingAverageParseTime = _segmentEncryptedParseTimeMA[segment].Average,
                    UnencryptedMovingAverageParseTime = _segmentUnencryptedParseTimeMA[segment].Average,
                    
                    // 压缩状态统计
                    CompressedCount = compressedResults.Count,
                    UncompressedCount = uncompressedResults.Count,
                    CompressedAverageParseTime = compressedResults.Count > 0 ? compressedResults.Average(r => r.ParseTimeMs) : 0,
                    UncompressedAverageParseTime = uncompressedResults.Count > 0 ? uncompressedResults.Average(r => r.ParseTimeMs) : 0,
                    CompressedMovingAverageParseTime = _segmentCompressedParseTimeMA[segment].Average,
                    UncompressedMovingAverageParseTime = _segmentUncompressedParseTimeMA[segment].Average,
                    CompressedAverageDataSize = compressedResults.Count > 0 ? compressedResults.Average(r => r.MessageSize / 2.0) : 0,
                    UncompressedAverageDataSize = uncompressedResults.Count > 0 ? uncompressedResults.Average(r => r.MessageSize / 2.0) : 0
                };
            }
        }
    }

    /// <summary>
    /// 详细统计信息
    /// </summary>
    public class DetailedStats
    {
        public int TotalTests { get; set; }
        public double SuccessRate { get; set; }
        public TimeSpan RunningTime { get; set; }
        public OperationStats BuildStats { get; set; } = new();
        public OperationStats SerializeStats { get; set; } = new();
        public OperationStats ParseStats { get; set; } = new();
        public SystemResourceStats SystemStats { get; set; } = new(); // 新增
        public ComparisonStats EncryptionComparison { get; set; } = new();
        public ComparisonStats CompressionComparison { get; set; } = new();
        public ThroughputStats Throughput { get; set; } = new();
    }

    /// <summary>
    /// 操作统计
    /// </summary>
    public class OperationStats
    {
        public double Average { get; set; }
        public double Min { get; set; }
        public double Max { get; set; }
        public double Median { get; set; }
        public double P95 { get; set; }
        public double P99 { get; set; }
        public double MovingAverage { get; set; } // 千次移动平均
    }

    /// <summary>
    /// 系统资源统计
    /// </summary>
    public class SystemResourceStats
    {
        public double AverageCpuUsage { get; set; }
        public double MinCpuUsage { get; set; }
        public double MaxCpuUsage { get; set; }
        public double MovingAverageCpuUsage { get; set; }
        
        public double AverageMemoryUsageMB { get; set; }
        public double MinMemoryUsageMB { get; set; }
        public double MaxMemoryUsageMB { get; set; }
        public double MovingAverageMemoryUsageMB { get; set; }
    }

    /// <summary>
    /// 对比统计
    /// </summary>
    public class ComparisonStats
    {
        public int WithFeatureCount { get; set; }
        public int WithoutFeatureCount { get; set; }
        public double WithFeatureAverage { get; set; }
        public double WithoutFeatureAverage { get; set; }
        public double Overhead { get; set; }
        public double WithFeatureSize { get; set; }
        public double WithoutFeatureSize { get; set; }
    }

    /// <summary>
    /// 吞吐量统计
    /// </summary>
    public class ThroughputStats
    {
        public double TestsPerSecond { get; set; }
        public double BuildsPerSecond { get; set; }
        public double ParsesPerSecond { get; set; }
    }

    /// <summary>
    /// 数据大小分段枚举
    /// </summary>
    public enum DataSizeSegment
    {
        /// <summary>
        /// 小消息: 0-1KB
        /// </summary>
        Small = 0,
        
        /// <summary>
        /// 中等消息: 1KB-10KB
        /// </summary>
        Medium = 1,
        
        /// <summary>
        /// 大消息: 10KB-100KB
        /// </summary>
        Large = 2,
        
        /// <summary>
        /// 超大消息: >100KB
        /// </summary>
        ExtraLarge = 3
    }

    /// <summary>
    /// 按数据大小分段的解析时间统计
    /// </summary>
    public class ParseTimeSegmentStats
    {
        public DataSizeSegment Segment { get; set; }
        public string SegmentName { get; set; } = string.Empty;
        public int Count { get; set; }
        public double AverageParseTime { get; set; }
        public double MinParseTime { get; set; }
        public double MaxParseTime { get; set; }
        public double MovingAverageParseTime { get; set; }
        public double AverageDataSize { get; set; }
        public long TotalDataProcessed { get; set; }
        
        // 新增：加密状态细分统计
        public int EncryptedCount { get; set; }
        public int UnencryptedCount { get; set; }
        public double EncryptedAverageParseTime { get; set; }
        public double UnencryptedAverageParseTime { get; set; }
        public double EncryptedMovingAverageParseTime { get; set; }
        public double UnencryptedMovingAverageParseTime { get; set; }
        
        // 新增：压缩状态细分统计  
        public int CompressedCount { get; set; }
        public int UncompressedCount { get; set; }
        public double CompressedAverageParseTime { get; set; }
        public double UncompressedAverageParseTime { get; set; }
        public double CompressedMovingAverageParseTime { get; set; }
        public double UncompressedMovingAverageParseTime { get; set; }
        public double CompressedAverageDataSize { get; set; }
        public double UncompressedAverageDataSize { get; set; }
        
        /// <summary>
        /// 解析吞吐量 (KB/s)
        /// </summary>
        public double ThroughputKBps => AverageParseTime > 0 ? (AverageDataSize / 1024.0) / (AverageParseTime / 1000.0) : 0;
        
        /// <summary>
        /// 加密数据解析吞吐量 (KB/s)
        /// </summary>
        public double EncryptedThroughputKBps => EncryptedAverageParseTime > 0 ? (AverageDataSize / 1024.0) / (EncryptedAverageParseTime / 1000.0) : 0;
        
        /// <summary>
        /// 不加密数据解析吞吐量 (KB/s)
        /// </summary>
        public double UnencryptedThroughputKBps => UnencryptedAverageParseTime > 0 ? (AverageDataSize / 1024.0) / (UnencryptedAverageParseTime / 1000.0) : 0;
        
        /// <summary>
        /// 压缩数据解析吞吐量 (KB/s)
        /// </summary>
        public double CompressedThroughputKBps => CompressedAverageParseTime > 0 ? (CompressedAverageDataSize / 1024.0) / (CompressedAverageParseTime / 1000.0) : 0;
        
        /// <summary>
        /// 不压缩数据解析吞吐量 (KB/s)
        /// </summary>
        public double UncompressedThroughputKBps => UncompressedAverageParseTime > 0 ? (UncompressedAverageDataSize / 1024.0) / (UncompressedAverageParseTime / 1000.0) : 0;
        
        /// <summary>
        /// 加密性能开销 (ms)
        /// </summary>
        public double EncryptionOverhead => EncryptedAverageParseTime - UnencryptedAverageParseTime;
        
        /// <summary>
        /// 压缩性能开销 (ms)
        /// </summary>
        public double CompressionOverhead => CompressedAverageParseTime - UncompressedAverageParseTime;
        
        /// <summary>
        /// 压缩比例 (%)
        /// </summary>
        public double CompressionRatio => UncompressedAverageDataSize > 0 ? (1 - CompressedAverageDataSize / UncompressedAverageDataSize) * 100 : 0;
    }
}